//
//  XLAudioSpectrumPlayer.m
//  AudioWaveDemo
//
//  Created by ilongge on 2023/4/19.
//

#import "XLAudioSpectrumPlayer.h"

@implementation XLAudioSpectrumPlayer
- (instancetype)init
{
    self = [super init];
    if (self) {
        _fftsize = 2048;
        _player = [[AVAudioPlayerNode alloc] init];
        _engine = [[AVAudioEngine alloc] init];
        [_engine attachNode:_player];
        [_engine connect:_player to:_engine.mainMixerNode format:nil];
        
        [_engine prepare];
        NSError *error = nil;
        [_engine startAndReturnError:&error];
        if (error) {
            NSLog(@"%@", error);
        }
    }
    return self;
}

- (NSData *)convert:(AVAudioPCMBuffer *)pcmBuffer sampleBlock:(void (^)(NSData *, BOOL))sampleBlock
{
    NSInteger channelCount = pcmBuffer.format.channelCount;
    NSInteger length = pcmBuffer.frameLength * channelCount;
    NSData *data = [NSData dataWithBytes:pcmBuffer.floatChannelData[0] length:length * sizeof(float)];
    if (sampleBlock){
        sampleBlock(data, self.player.isPlaying==NO);
    }
    return data;
}

- (void)play:(NSString *)filePath sampleBlock:(void (^)(NSData *, BOOL))sampleBlock
{
    NSURL *audioUrl = [NSURL fileURLWithPath:filePath];
    if (audioUrl) {
        NSError *error = nil;
        AVAudioFile *audioFile = [[AVAudioFile alloc] initForReading:audioUrl error:&error];
        if (error == nil) {
            [self.player stop];
            [self.engine.mainMixerNode removeTapOnBus:0];
            [self.engine.mainMixerNode installTapOnBus:0
                                        bufferSize:(AVAudioFrameCount)self.fftsize
                                            format:nil
                                             block:^(AVAudioPCMBuffer * _Nonnull buffer, AVAudioTime * _Nonnull when) {
                if(self.player.isPlaying == NO){
                    return;
                }
                [self convert:buffer sampleBlock:sampleBlock];
            }];
            [self.player scheduleFile:audioFile atTime:nil completionHandler:nil];
            [self.player play];
        }
        else{
            NSLog(@"读取音频文件失败--audioFile读取失败");
        }
    }
    else{
        NSLog(@"读取音频文件失败--URL创建失败");
    }
}

- (void)stop
{
    [self.player stop];
}

- (NSArray <NSNumber *> *)fft:(AVAudioPCMBuffer *)buffer
{
    NSMutableArray <NSNumber *> * array = [NSMutableArray<NSNumber *> array];
    float * const* floatChannelData = buffer.floatChannelData;
    if (floatChannelData) {
        float * const*  channels = floatChannelData;
        int channelCount = buffer.format.channelCount;
        BOOL isInterleaved = buffer.format.isInterleaved;
        if (isInterleaved) {
            NSData *data = [NSData dataWithBytes:floatChannelData length:self.fftsize * channelCount];
            NSMutableArray *channelsTemp = [[NSMutableArray <NSNumber *>  alloc] init];
            for (NSInteger index = 0; index < channelCount; index ++ ) {
                
            }
        }
    }
    return array;
}
@end
